import 'package:account/bean/group.dart';
import 'package:account/utils/cus_behavior.dart';
import 'package:account/utils/my_data.dart';
import 'package:account/utils/utils.dart';
import 'package:flutter/material.dart';

import '../utils/utils.dart';

Account? _account;
bool _addOrUpdate = false; //当前模式，添加为true，更新为false
///分组选择的下表，对应[QUtils.listGroup]的下标
int _groupValue = 0;

class AddApp extends StatefulWidget {
  final int index;
  final int position;

  AddApp(this.index, this.position) {
    _addOrUpdate = this.index == -1;
    if (index == -1) {
      _account = Account();
      _account!.list!.add(AccountState(key: "名称"));
    } else {
      _account = QUtils.listGroup[index].list![position];
    }
  }

  @override
  State<StatefulWidget> createState() {
    return AddState();
  }
}

class AddState extends State {
  List<AccountState>? list = _account!.list!;
  String _tip = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("账号管理"),
          actions: [
            Container(
                alignment: Alignment.center,
                child: TextButton(
                    onPressed: () {
                      list!.add(AccountState());
                      setState(() {});
                    },
                    child: Text("添加一行",
                        style: TextStyle(color: Colors.white, fontSize: 20)))),
            Container(
                padding: EdgeInsets.only(right: 10),
                alignment: Alignment.center,
                child: TextButton(
                    onPressed: () {
                      //保存或者更新账号密码到数据库
                      _savePressed(context);
                    },
                    child: Text("保存",
                        style: TextStyle(color: Colors.white, fontSize: 20)))),
          ],
        ),
        body: Column(
          children: [
            Container(
              width: MediaQuery.of(context).size.width,
              height: 50,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  Positioned(
                      left: 15,
                      child: Text(_account!.gName == ""
                          ? "当前未选择分组"
                          : "已选分组：${_account!.gName}")),
                  Positioned(
                      right: 15,
                      child: ElevatedButton(
                          child: Text("选择分组"),
                          onPressed: () async {
                            Object? result = await showDialog(
                                barrierDismissible: false,
                                context: context,
                                builder: (context) {
                                  return DialogWidget();
                                });
                            if (result != null) {
                              int tempIndex = result as int;
                              _account!.gId = QUtils.listGroup[tempIndex].id!;
                              _account!.gName =
                                  QUtils.listGroup[tempIndex].name!;
                              setState(() {});
                            }
                          }))
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.only(top: 10),
              child: Visibility(
                visible: _tip != "",
                child: Text(_tip,
                    style: TextStyle(color: Colors.red, fontSize: 16)),
              ),
            ),
            Expanded(
                child: ScrollConfiguration(
              behavior: CusBehavior(),
              child: ListView.builder(
                  itemCount: list!.length,
                  itemBuilder: (BuildContext context, int index) {
                    return AddItem(list!, index, refreshState);
                  }),
            ))
          ],
        ));
  }

  void refreshState() {
    setState(() {});
  }

  ///保存或者更新按钮内容
  _savePressed(BuildContext context) async {
    //判断分组
    if (_account!.gId == -1) {
      _tip = "未选择分组!";
      setState(() {});
      return;
    }
    //保存到数据库
    //判断是否有效
    if (_account!.isValid()) {
      //添加时间到对象中
      _account!.time = DateTime.now().millisecondsSinceEpoch;
      //判断是添加还是更新
      if (_addOrUpdate) {
        //添加
        //保存内容到数据库
        if (await MyData.saveAccountWithGroup(_account!, _groupValue)) {
          print("保存成功");
          //更新list
          await MyData.getAllGroupAndAccount();
          //保存成功，关闭掉当前页面
          Navigator.pop(context, 1);
          return;
        } else {
          _tip = "名称已存在!";
        }
      } else {
        //更新
        switch (await MyData.updateAccountWithGroup(_account, _groupValue)) {
          case 0: //保存成功
            await MyData.getAllGroupAndAccount();
            Navigator.pop(context, 1);
            return;
          case 1:
            _tip = "未找到相关账号!";
            break;
          case 2:
            _tip = "已存在相同名称的账号!";
            break;
        }
      }
    } else {
      _tip = "值不能为空!";
    }
    setState(() {});
  }
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
///选择分组的dialog布局
class DialogWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return DialogState();
  }
}

class DialogState extends State {
  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(top: 40, left: 10, right: 10),
        child: Wrap(
          children: _createList().toList(),
        ));
  }

  List<Widget> _createList() {
    List<Widget> list = [];
    list.add(Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          "当前分组：${QUtils.listGroup[_groupValue].name!}",
          style: TextStyle(
              color: Colors.white,
              fontSize: 16,
              decoration: TextDecoration.none),
        ),
        Container(
          margin: EdgeInsets.only(left: 10),
          child: ElevatedButton(
            child: Text("确定"),
            onPressed: () {
              Navigator.pop(context, _groupValue);
            },
          ),
        )
      ],
    ));
    for (int i = 0; i < QUtils.listGroup.length; i++) {
      list.add(Container(
          margin: EdgeInsets.only(left: 10, right: 10),
          child: ElevatedButton(
              onPressed: () {
                _groupValue = i;
                setState(() {});
              },
              child: Text(QUtils.listGroup[i].name!))));
    }
    return list;
  }
}

class AddItem extends StatefulWidget {
  final List<AccountState> account;
  final int position;
  final VoidCallback callback;

  AddItem(this.account, this.position, this.callback);

  @override
  State<StatefulWidget> createState() {
    return AddItemState(account, position, callback);
  }
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

///实际key value 内容的listView
class AddItemState extends State {
  List<AccountState> list;
  int position;
  VoidCallback callback;

  AddItemState(this.list, this.position, this.callback);

  @override
  Widget build(BuildContext context) {
    //监听文本变化修改相关的值
    TextEditingController keyCon = TextEditingController();
    TextEditingController valueCon = TextEditingController();
    keyCon.addListener(() {
      list[position].key = keyCon.text;
    });
    valueCon.addListener(() {
      list[position].value = valueCon.text;
    });
    //赋值内容
    if (list[position].key != null) keyCon.text = list[position].key!;
    if (list[position].value != null) valueCon.text = list[position].value!;
    //如果是第一行则不允许key的编辑
    bool _isEnableKey = position != 0;
    //如果是第一行则隐藏删除组件
    double _opacity = position == 0 ? 0 : 1;

    return Container(
      width: MediaQuery.of(context).size.width,
      child: Flex(
        direction: Axis.horizontal,
        children: [
          Expanded(
              flex: 3,
              child: Container(
                padding: EdgeInsets.only(left: 20, right: 20),
                child: TextField(
                  enabled: _isEnableKey,
                  textAlign: TextAlign.center,
                  controller: keyCon,
                ),
              )),
          Expanded(
              flex: 6,
              child: Container(
                padding: EdgeInsets.only(right: 20),
                child: TextField(
                  controller: valueCon,
                ),
              )),
          Expanded(
              flex: 1,
              child: Opacity(
                opacity: _opacity,
                child: Container(
                    alignment: Alignment.center,
                    child: IconButton(
                      icon: Icon(Icons.delete, color: Colors.blue),
                      onPressed: () {
                        if (position == 0) return;
                        list.removeAt(position);
                        callback();
                      },
                    )),
              ))
        ],
      ),
    );
  }
}
